<?php
/* 
 * 专用于第三方订单接口对接公共方法，不登录亦可操作，适用于定时计划执行
 */
class OrderAPIAction extends Action {

  public function __construct()
  {
    import('@.ORG.Nusoap.nusoap','','.php');
    spl_autoload_register(array('Think','autoload'));   //必须重置，否则造成原TP类无法识别
    
  }
   
   //初始化德生堂SOAP
  private function getDst(){
     //$dst_wsdl = "http://114.110.9.28:8099/hydee_stare.asmx?WSDL"; //10-07 11:26临时测试用几天
    //$dst_wsdl = "http://118.145.11.241:8099/hydee_stare.asmx?WSDL";
    $dst_wsdl = "http://websh.111yao.cn:8099/hydee_stare.asmx?WSDL";
    $dst = array(
       'wsdl' => $dst_wsdl,
       //'username' => "dyw",
       'username' => "1464",
      'pwd' => "dyw@789",
      //'pwd' => "dst20130901",
      'client' => new nusoap_client($dst_wsdl,'wsdl','','','','',900,900), //timeout=900
      );
    return $dst;
  }

  //初始化吉信通短信SOAP
  //默认是非营销类短信通知 
  private function getJXT($is_marketing = 0){
    $jxt_wsdl = "http://service2.winic.org/Service.asmx?WSDL";
    $jxt = array(
       'wsdl' => $jxt_wsdl,
      'pwd' => M('Configure')->where('var_name = "msg_pwd"')->getField('value'),
      'client' => new nusoap_client($jxt_wsdl,'wsdl','','','','',900,900), //timeout=900
      );
    if($is_marketing){
        $jxt['username'] = M('Configure')->where('var_name = "msg_marketing_account"')->getField('value'); 
    }else{
        $jxt['username'] = M('Configure')->where('var_name = "msg_account"')->getField('value'); 
    }


    return $jxt;
  }

   /**德生堂订单
   **通过时间区段获取相应的订单概要信息，返回订单数组
   **@$start_time string:2013-08-29T20:46:02 开始时间
   *@$end_time string:2013-08-31T20:46:02 开始时间 xml时间格式
   **/ 
  public function getDstOrderByTime($start_time="",$end_time="")
  {  
      $dst = $this->getDst();
      $parm=array('partnerno'=>$dst['username'],'pass'=>$dst['pwd'],'rq_begin'=>$start_time,'rq_end'=>$end_time);
      $result = $dst['client']->call('Get_partnerorder', $parm,$namespace='http://tempuri.org', $soapAction='http://tempuri.org/Get_partnerorder');
      
      if($result === false)
        return NULL;
      $rsxml = $result['Get_partnerorderResult'];
      if(empty($rsxml) ) //防止有意外报错发生
        return NULL;
      $orders = new SimpleXMLElement($rsxml);
      if($orders->result->flag == 'true')
          return $orders->data;
      else
          return NULL;
  }

  
  /**
  *获取德生堂订单概要信息
  *@orderno 德生堂订单号
  *返回特定格式的一个订单数组，不包括订单商品明细
  **/
  public function getDstOrderView($orderno='')
  {
      $dst = $this->getDst();
      $order_detail_param = array('partnerno'=>$dst['username'],'pass'=>$dst['pwd'],'orderno'=>$orderno );
      $order_view = $dst['client']->call('Get_partnerorderM', $order_detail_param,$namespace='http://tempuri.org', $soapAction='http://tempuri.org/Get_partnerorderM');
      if($order_view === false)
        return null;
      $rsxml = $order_view['Get_partnerorderMResult'];
      if(empty($rsxml) ) //防止有意外报错发生
        return NULL;
      $order = new SimpleXMLElement($rsxml);
      if($order->result->flag == 'true')
          return $order->data;
      else
          return null;
  }

  /**
  *获取德生堂订单 商品明细 信息
  *@orderno 德生堂订单号
  *返回特定格式的多个订单商品明细
  **/
  public function getDstOrderDetail($orderno='')
  { 
      $dst = $this->getDst();
      $order_detail_param = array('partnerno'=>$dst['username'],'pass'=>$dst['pwd'],'orderno'=>$orderno );
      $order_view = $dst['client']->call('Get_partnerorder_detial', $order_detail_param,$namespace='http://tempuri.org', $soapAction='http://tempuri.org/Get_partnerorder_detial');
      if($order_view === false)
        return null;
      $rsxml = $order_view['Get_partnerorder_detialResult'];
      if(empty($rsxml) ) //防止有意外报错发生
        return NULL;
      $order = new SimpleXMLElement($rsxml);
      if($order->result->flag == 'true')
          return $order->data;
      else
          return null;
  }

    /**
  *获取德生堂订单 商品明细 信息
  *@orderno 德生堂订单号
  *返回特定格式的多个订单商品明细
  **/
  public function setDstOrderDown($orderno='')
  {
      $dst = $this->getDst();
      $order_detail_param = array('partnerno'=>$dst['username'],'pass'=>$dst['pwd'],'orderno'=>$orderno );
      $order_view = $dst['client']->call('Set_partnerorder_dowm', $order_detail_param,$namespace='http://tempuri.org', $soapAction='http://tempuri.org/Set_partnerorder_dowm');
     
      if($order_view === false)
        return false;
      $rsxml = $order_view['Set_partnerorder_dowmResult'];
      if(empty($rsxml) ) //防止有意外报错发生
        return false;
      $order = new SimpleXMLElement($rsxml);
      if($order->result->flag == 'true')
          return true;
      else
          return false;
  }

  /**德生堂发货
  ** $orderno:德生堂订单号
  ** $logino: 快递单号
  ** $logicompany_id:快递公司编号，需编译：必须使用德生堂对应的快递编号TODO
  **
  ** @Return 如果发货成功，则返回true,否则false
  **/
  public function dst_shipping($orderno,$logino,$logicompany_id){
    
    ignore_user_abort();//关掉浏览器，PHP脚本也可以继续执行.
    $logicompany_id = $this->getDstExpressId($logicompany_id);

    $dst = $this->getDst();
      $order_detail_param = array('partnerno'=>$dst['username'],'pass'=>$dst['pwd'],'orderno'=>$orderno,
        'expid'=> $logino, 'expcmpid'=>$logicompany_id );
      $shipping = $dst['client']->call('Set_partnerorder_back', $order_detail_param,$namespace='http://tempuri.org', $soapAction='http://tempuri.org/Get_partnerorderM');
     
      if($shipping === false)
        return false;
      $rsxml = $shipping['Set_partnerorder_backResult'];
      if(empty($rsxml) ) //防止有意外报错发生
        return false;
      $order = new SimpleXMLElement($rsxml);
      if($order->result->flag == 'true'){
        //is_shipping_mall = 1;
        M('Sale')->where('sale_no = "'.$orderno.'"')->setField('is_shipping_mall',1);
        return true;
      }
          
      else
          return false; //发货失败

  }

  /**德生堂发货
  ** $orderno:德生堂订单号
  ** $logino: 快递单号
  ** $logicompany_id:快递公司编号，需编译：必须使用德生堂对应的快递编号TODO
  **
  ** @Return 如果发货成功，则返回true,否则false
  **/
  public function dst_shipping_manual($orderno,$logino,$logicompany_id){
    $orderno = empty($_REQUEST['orderno']) ? $orderno : $_REQUEST['orderno'];
    $logino = empty($_REQUEST['logino']) ? $logino : $_REQUEST['logino'];
    $logicompany_id = empty($_REQUEST['logicompany_id']) ? $logicompany_id : $_REQUEST['logicompany_id'];

    ignore_user_abort();//关掉浏览器，PHP脚本也可以继续执行.
    $logicompany_id = $this->getDstExpressId($logicompany_id);

    $dst = $this->getDst();
      $order_detail_param = array('partnerno'=>$dst['username'],'pass'=>$dst['pwd'],'orderno'=>$orderno,
        'expid'=> $logino, 'expcmpid'=>$logicompany_id );
      $shipping = $dst['client']->call('Set_partnerorder_back', $order_detail_param,$namespace='http://tempuri.org', $soapAction='http://tempuri.org/Get_partnerorderM');
     
      if($shipping === false)
        A('Public')->error("德生堂服务器暂时无法连接，请稍后再试！" ,false,5 ); 
      $rsxml = $shipping['Set_partnerorder_backResult'];
      if(empty($rsxml) ) //防止有意外报错发生
      { header("Content-type:text/html;charset=utf-8");
        dump($shipping);
         A('Public')->error("发货失败，点击返回！",false,20); 
      }
      $order = new SimpleXMLElement($rsxml);
      if($order->result->flag == 'true'){
        //is_shipping_mall = 1;
        M('Sale')->where('sale_no = "'.$orderno.'"')->setField('is_shipping_mall',1);
        A('Public')->success("德生堂发货成功！");
      }
          
      else
      {  header("Content-type:text/html;charset=utf-8");
         dump($shipping);
         A('Public')->error("发货失败，点击返回！",false,20); 
      }

  }
  /**
  **同步德生堂订单，如果没有指定起止时间，则按系统内已经下载成功的最近订单时间为起止时间获取订单
  **  默认只接收待发货的订单--status状态为1的
  **/
  public function sync_dst($start_time="",$end_time="")
  { set_time_limit(0);
    ignore_user_abort();//关掉浏览器，PHP脚本也可以继续执行.
    $sale_detail = M('Sale_detail');
    $sale = M('Sale');
    $customer = M('Customer');
    $shipping_address = M('Shipping_address');

    $total = 0; //total money =>overview table
    $sum_number = 0; //sum total number

    //$start_time = "2013-09-04T09:00:33";
    //$end_time = "2013-09-01T15:15:33";

    if(empty($start_time)){ //最新订单时间 已下载完成的
      $map_nodown = array(
         'create_time' => array('gt',time()-24*60*60),
         'order_source_id' => 5,
         'down_status' => 0 ,
         'length("sale_no")' => array('lt',11) , //except Bufa order and branch order like w5
      );
      $latest_nodown_create_time = $sale->where($map_nodown)->min('create_time');
      $latest_create_time =empty($latest_nodown_create_time) ? $sale->where('order_source_id = 5 and down_status =1')->max('create_time')
                                                             : $latest_nodown_create_time ;
    }
    $now = time();
    $start_time = empty($start_time) ? toDate($latest_create_time,'Y-m-d\TH:i:s') : $start_time;
    $end_time = empty($end_time) ? toDate($now,'Y-m-d\TH:i:s') : $end_time;
    $raw_orders = $this->getDstOrderByTime($start_time,$end_time);
    if ($raw_orders === NULL ) {
      //A('Public')->error("德生堂订单获取失败！");
      exit;
    }
    $mass_sale_data = array(); //临时存放批量订单数据
    $i = 0;
    if(empty($raw_orders->row)){
      exit;
      //A('Public')->error("暂无德生堂订单！请稍后同步！");
    }
    foreach ($raw_orders->row as $key => $order) {
        if( (string)$order->status == 1  //待发货的订单  
          //&& getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ) != 0 //过滤掉待付款的订单 --未创建支付宝交易
          && !$downstatus = (string)$order->downstatus){//下载未下载过的
           $sdata = array(
               'sale_no' => (string)$order->ptorderno,
               //'mall_no' => (string)$order->orderno, //第三方订单号 在商品里完善
               'customer_name' => (string)$order->olcustid,//会员名
               //'alipay' => (string)$order->alipay, //TODO
               'total' => ((float)$order->amount-(float)$order->freight), //货款
               'logifee' => (float)$order->freight, //运费
               'sum_pay' => (float)$order->amount, //理论应付款：总金额，有可能包括对方货款
               //我方应付款= 我方货款+运费
               'should_pay' => (float)$order->amount,    
               'real_pay' => (float)$order->amount,  //买家实际支付金额,可能包含第三方货款
               // 订单状态转换统一的
               'order_status' => (string)$order->status == 1 ? 2 :($order->status == 3 ? 3:0 ) , //如果对方状态是1，则转为待发货2; 若3则3已发货，其他 为0

               'customer_msg' => (string)$order->buyer_message,
               'create_time' => empty($order->createtime) ? 0: strtotime((string)$order->createtime),
               'pay_time' => empty($order->paytime) ? 0: strtotime( (string)$order->paytime ),  //支付时间
               //默认不存在对应的运单号及快递，是需要待发货的订单
               //'logicompany_id' => empty($order->expcmpid) ? 0: getDstExpressId( (string)$order->expcmpid), // exchange to id
               //'logino' => empty($order->expid)? '' : (string)$order->expid, 
        
               //'invoice_title' => trim((string)$order->invoice), //TODO 无法获取

               //shipping address info
               'shipping_name' => (string)$order->receiver_name,
               'address' => (string)$order->receiver_address,
               'phone' => (string)$order->receiver_phone,
               'mobile' => (string)$order->receiver_mobile,
               'remark' => (string)$order->notice , //商家备注
               'order_source_id' => $this->getDstShopId($order->olshopid), //德生堂几个来源订单
               'warehouse_id' => 1,
               'user_id' => empty($_SESSION[C('USER_AUTH_KEY')])? 0 : $_SESSION[C('USER_AUTH_KEY')],
               //'sum_number' => getSumNumber( trim($data['0']) ), TODO
               'province' => (string)$order->receiver_state, //省份
               'city' => (string)$order->receiver_city, 
               'county' => (string)$order->receiver_district,  //区或县
           );
            $sdata['address'] = $sdata['province'].' '.$sdata['city'].' '.$sdata['county'].' '.$sdata['address'];
           
               // 新增会员 或获取已有会员ID 淘宝可用 如果是官网订单，TODO
           $customer_id = getCustomerId($sdata['customer_name'],'');
           $sdata ['customer_id'] = $customer_id ;
           $shipping_address_id = getShippingAddressId($customer_id ,$sdata['shipping_name'],$sdata['address'],$sdata['mobile'],$sdata ['phone'] );
           $sdata ['shipping_address_id'] = $shipping_address_id ;
           //$sale_id = $sale -> add($sdata);
           $mass_sale_data[$i] = $sdata; //存入批量订单数组
           $i++; 
           
           //unset
           unset($sdata);
           //sleep(0.1);
          } 
          
        }//end sale foreach
        //new sale_data
        $all_sale_data = $mass_sale_data; //stock all sale data
        $order_no = array();
        foreach($mass_sale_data as $key=>$val){
          $order_no[$val['sale_no']] = $val['sale_no'];
        }
        $map = array('sale_no'=>array('in',$order_no));
        $is_exists = $sale->where($map)->getField('id,sale_no');
        if ($is_exists){
          foreach($is_exists as $exist_sale_no){ //循环去掉已经存在的订单
            foreach ($mass_sale_data as $key => $value) {
              if($value['sale_no'] == $exist_sale_no ){
                unset($mass_sale_data[$key]);
                break;
              }
                
            }
          }
        } 

        //mass insert sale data to sale table 一次性插入速度会更快
        //TODO 检查原平台订单号是否已存在，防止因对方数据混乱而生成新订单号，造成重复插入
        $mass_sale_data = array_values($mass_sale_data); //rebuild index
        if($mass_sale_data);
          $said = $sale->addAll($mass_sale_data);  //插入新订单
        $i = 0;
        $cache_goods = S('goods'); //缓存的商品信息
        foreach ($all_sale_data as $sigle_order) {
          //未下载成功，则处理商品明细
          $tmp_order = $sale->where('sale_no ="'.$sigle_order['sale_no'].'"')->field('id,down_status')->find();

          if(!$down_status = $tmp_order['down_status'] ){
                
                $sdetails = $this->getDstOrderDetail($sigle_order['sale_no']);
                if(!$sdetails->row) 
                  continue;
                //处理商品明细
                $mass_gdata = array();
                $k = 0;
                $new_data = array(); //整理后订单数据，包括mall_no,sum_number
                foreach ($sdetails->row as $goods) {
                  if($rs = $sale_detail->where('product_id = '.(int)$goods->wareid.' and sale_id = '.$tmp_order['id'] )->getField('id') )
                    continue;//如果已经有重复商品记录，则跳过处理

                    $gdata = array(
                         'sale_no' => (string)$goods->ptorderno,
                         'sale_title' => (string)$goods->warename, //TODO 以后用twarename代替
                         'price' => (float)$goods->price,
                         'number' => (int)$goods->num,
                         'total' => (float)$goods->price* (int)$goods->num,
                         'out_number' => (string)$goods->wareid,
                         //'options' => (string)$goods->options, //TODO
                         'warehouse_id' => 1, //默认第一个仓库
                         'product_id' => (int)$goods->wareid,  //对应货品ID，不是产品； TODO 德生堂传过来的PID即此
                         'sale_id' => $tmp_order['id'],
                         'create_time' => time(),

                     );
                    $new_warehouse_id = intval($cache_goods[$gdata['product_id']]['warehouse_id']); //根据货品仓库更新订单商品仓库
                    $gdata['warehouse_id'] = $new_warehouse_id == 0 ? 1 : $new_warehouse_id; //如果为0,则取默认仓库 
                    $total += $gdata['total'];
                    $sum_number += $gdata['number'];
                    //回归淘宝原始订单号
		            if( !empty($new_data['mall_no']) && strpos($new_data['mall_no'], (string)$goods->orderno) === false )
                        $new_data['mall_no'] .= ",". (string)$goods->orderno;   //合并订单
		            else
                        $new_data['mall_no'] = (string)$goods->orderno;
                    $this->resetObject($goods);
                    //由于德生堂系统问题,合并订单中有重复商品,不能去重.其他单一订单则可以去重
                    if( strpos( $new_data['mall_no'],',' ) !== false ){//合并订单，则不去重
                       $mass_gdata[$k] = $gdata;
                       $k ++;
                    }else//单一订单
                       $mass_gdata[$gdata['product_id']] = $gdata; 
                       //以产品编号为索引，可以去掉重复的商品记录
                       
                }
                //rebuild array index
                $mass_gdata = array_values($mass_gdata);
                //mass insert goods detail into sale table
                $sdid =  $sale_detail->addAll($mass_gdata);
                unset($gdata);
                unset($mass_gdata);
                $k = 0;

                if($sdid){
                   $new_data['down_status'] = 1; //设置已经下载成功
                    $new_data['total'] = $total;
                    $new_data['sum_number'] = $sum_number; 
                    $save_id = $sale->where('id = '.$tmp_order['id'])->save($new_data);
                    $this->setDstOrderDown( $sigle_order['sale_no'] );  //回传设置订单已下载
                    $i ++;
                }
                
                $total = 0;
                $sum_number = 0;
                sleep(3);

                if( $i == 70 )  //如果下载订单数超过70,则停止下载 ,留给下一轮,防止赠品重复赠送.
                    break;
           }//end 处理商品明细
        }
        $this->auto_add_mass_gift(); //下载完毕，即绑定赠品
        SaleModel::auto_split_mass_order(); //拆单
    }

    //通过订单号同步德生堂某一个订单,可直接赋值或通过POST,GET传值-订单号
    public function syncDstSigleOrder($sale_no="")
    {
      $sale_no = empty($_REQUEST['sale_no']) ? trim($sale_no) : trim($_REQUEST['sale_no']);
      if(empty($sale_no))
        A('Public')->error("订单错误，请重新操作");

      $sale_detail = M('Sale_detail');
      $sale = M('Sale');

      $total = 0; //total money =>overview table
      $sum_number = 0; //sum total number
      //检查是否是德生堂订单
      $sigle_order = $sale->where('sale_no = "'.$sale_no.'" and (order_source_id =5 or order_source_id =6 or order_source_id = 8)')->find();
      if(!is_array($sigle_order))
          A('Public')->error("该订单不存在或不是德生堂订单！");

      //未下载成功，则处理商品明细
      if(!$down_status = $sigle_order['down_status'] ){
           $cache_goods = S('goods'); 
            
            $sdetails = $this->getDstOrderDetail($sigle_order['sale_no']);
            if(!$sdetails->row) 
              A('Public')->error("获取德生堂订单明细失败，请重试");
            //处理商品明细
            $mass_gdata = array();
            $k = 0;
            $new_data = array(); //整理后订单数据，包括mall_no,sum_number
            foreach ($sdetails->row as $goods) {
              if($rs = $sale_detail->where('product_id = '.(int)$goods->wareid.' and sale_id = '.$sigle_order['id'] )->getField('id') )
                continue;//如果已经有重复商品记录，则跳过处理

                $gdata = array(
                     'sale_no' => (string)$goods->ptorderno,
                     'sale_title' => (string)$goods->warename, //TODO 以后用twarename代替
                     'price' => (float)$goods->price,
                     'number' => (int)$goods->num,
                     'total' => (float)$goods->price* (int)$goods->num,
                     'out_number' => (string)$goods->wareid,
                     //'options' => (string)$goods->options, //TODO
                     'warehouse_id' => 1, //默认第一个仓库
                     'product_id' => (int)$goods->wareid,  //对应货品ID，不是产品； TODO 德生堂传过来的PID即此
                     'sale_id' => $sigle_order['id'],
                     'create_time' => time(),

                 );
                $new_warehouse_id = intval($cache_goods[$gdata['product_id']]['warehouse_id']); //根据货品仓库更新订单商品仓库
                $gdata['warehouse_id'] = $new_warehouse_id == 0 ? 1 : $new_warehouse_id; //如果为0,则取默认仓库 
                $total += $gdata['total'];
                $sum_number += $gdata['number'];
            //回归淘宝原始订单号
                if( !empty($new_data['mall_no']) && $new_data['mall_no'] != (string)$goods->orderno )
                    $new_data['mall_no'] .= ",". (string)$goods->orderno;   //合并订单
                else
                    $new_data['mall_no'] = (string)$goods->orderno;
                $this->resetObject($goods);
                //以产品编号为索引，可以去掉重复的商品记录
                $mass_gdata[$gdata['product_id']] = $gdata; 
                //$mass_gdata[$k] = $gdata;
                $k ++;
            }
            //rebuild array index
            $mass_gdata = array_values($mass_gdata);
            //mass insert goods detail into sale table
            $sdid =  $sale_detail->addAll($mass_gdata);
            unset($gdata);
            unset($mass_gdata);
            $k = 0;

            if($sdid){
               $new_data['down_status'] = 1; //设置已经下载成功
                $new_data['total'] = $total;
                $new_data['sum_number'] = $sum_number; 
                $save_id = $sale->where('id = '.$sigle_order['id'])->save($new_data);
                $this->setDstOrderDown( $sigle_order['sale_no'] );  //回传设置订单已下载
                A('Public')->success("订单同步成功");
            }
       }//end 处理商品明细
       else
         A('Public')->success("订单已经下载成功，勿需同步！");

    }

    /*获取德生堂对应的快递编号
    ** @logicompany_id 系统内的快递公司ID
    ** 返回德生堂对应的快递ID
    */
    public function getDstExpressId($logicompany_id=0)
    {
      $expcmpid = 0;  //德生堂对应的快递编号

      if($logicompany_id == 0 )
        return 0;

      switch ($logicompany_id) {
        case '17': //中通
          $expcmpid = 121;
          break;
        case '18': //汇通
          $expcmpid = 128;
          break;
        case '15': //顺丰
          $expcmpid = 109;
          break;
        case '27': //邮政小包
          $expcmpid = 133;
          break;
        case '20': //圆通
          $expcmpid = 120;
          break;
        case '19': //申通
          $expcmpid = 131;
          break;
        case '37': //天天
          $expcmpid = 123;
          break;
        case '22': //优速
          $expcmpid = 114;
          break;
        case '21': //YUNDA
          $expcmpid = 122;
          break;
        case '16': //EMS
          $expcmpid = 119;
          break;
        default:
          $expcmpid = 0;
          break;
      }

      return $expcmpid;

    }


    //药房网补发货：未将发货信息同步到药房网的，此功能可进行修复
  public function yaofang_mass_reshipping()
  {   set_time_limit(0);
      $begin_time = time()-24*60*60*10; //10 days ago
      $map = array(
        'order_source_id' => array('in',"1,2,3,9"), //京卫订单，包括药房网，京卫天猫，京卫京东
        'order_status' => 3, //shippinged
        'logicompany_id' => array('gt',0),
        'logino' => array('neq',''),
        'create_time' => array('gt',$begin_time),
        'is_shipping_mall' => 0 
          );
      $express = S('express');
      $sales = M('Sale')->where($map)->field('sale_no,logicompany_id,logino')->findAll();
      if(is_array($sales)){
        foreach ($sales as $value) {
          if(strlen($value['sale_no'])>7 ) //只传递京卫的单号，特征等于7
               continue;
          jw_shipping( $value['sale_no'],$express[$value['logicompany_id']]['name'],$value['logino'],$value['logicompany_id'] );
          sleep(1);
        }
        //$this->success("成功在药房网上发货 ".$i." 订单！");
    }            
  }

  //德生堂批量补发货：已经发货，但未同步到德生堂的，将重新传递发货信息到德生堂系统
  public function dst_mass_reshipping()
  {
    set_time_limit(0);
    $begin_time = time()-24*60*60*10; //10 days ago
    $dst_map = array(
      'order_status' => 3,
      'is_shipping_mall' => 0,
      'order_source_id' => 5,
      'logicompany_id' => array('gt',0),
      'create_time' => array('gt',$begin_time),
      );
    $no_orders = M('Sale')->where($dst_map)->field('sale_no,logino,logicompany_id')->findAll();
    if(is_array($no_orders))
    foreach ($no_orders as $value) {
        $this->dst_shipping($value['sale_no'],$value['logino'],$value['logicompany_id']);
        sleep(3);
    }
  }

    //全部平台重发货到对方平台
  public function all_reshipping($value='')
  {
    $this->yaofang_mass_reshipping();
    $this->dst_mass_reshipping();
  }


    private function resetObject($obj) {
        foreach ($obj as $key => $value) {
            $obj->$key = NULL;
        }
    }
  
   /*根据德生堂对应的店铺编号，返回我系统内德生堂对应的店铺编号
    ** @olshopid 德生堂系统内的店铺编号
    ** 返回德生堂对应的快递ID
    */
    public function getDstShopId($olshopid=0)
    {
      $dstid = 0;  
      if($olshopid == 0 )
        return 0;

      switch ($olshopid) {
        case '1': //德生堂天猫店
          $dstid = 5;
          break;
        case '2': //德生堂官网 111yao
          $dstid = 6;
          break;
        case '7': //德生堂京东店
          $dstid = 8;
          break;
        case '9': //德生堂一号店
          $dstid = 10;
          break;
        default:
          $dstid = 5;
     }
      return $dstid;
   }

   //自动绑定赠品
   public function auto_add_mass_gift(){
      GiftAction::auto_mass_add_gift();
   }

   //获取淘宝量子流量统计数据
   public function getAllLog(){
      WeblogAction::getAllLog();
   }

   /**
    *发短信通知
    *@mobiles 通知的手机号，多个手机号用,隔开,最多1000个号码
    *@message 短信通知内容，长度不超过65字
    *@is_marketing 是否是营销通知，默认非营销类信息
    *@schedule_time 定时发送时间，默认为空，即时发送 格式2008-08-19 09:10:00
   **/
   public function sendMessages($mobiles,$message='',$is_marketing=0,$schedule_time="")
   {
      if(empty($mobiles) || empty($message) )
        return false;
      $jxt = $this->getJXT($is_marketing);
      $msg_param = array('uid'=>$jxt['username'],'pwd'=>$jxt['pwd'],'tos'=>$mobiles,'msg'=>$message,'otime'=>$schedule_time);
      $msg_detail = $jxt['client']->call('SendMessages', $msg_param,$namespace='http://tempuri.org', $soapAction='http://tempuri.org/SendMessages');
      $od = $msg_detail['SendMessagesResult'];
      //返回结果是16位数字，则表示发送成功
      if(is_numeric($od) && strlen($od) == 16 ) 
        return true;
      else
        return false;
   }

}
?>
